import re
import pandas as pd
from pandas import DataFrame


class TrainText (): #Train_Text
    
    def __init__(self,mode) -> None:
        self.Data = None
        self.word_list = []
        self.mat = [] #mat[i][j]=1说明第i个词语是第j个词语的子串
        self.col = 0
        self.datasize = 0

        path = '../database/' + mode + '_TrainData_Text.csv'
        self.Data = pd.read_csv(path)
        self.col = self.Data.shape[1]
        self.datasize = self.Data.shape[0]

        for i in range (1,self.Data.shape[1]):
            word = self.Data.iloc[:,i].name
            self.word_list.append(word)
        
        self.__InitMat()


    def __InitMat (self): #初始化mat矩阵
        length = len(self.word_list)

        for i in range (0,length): #初始化矩阵
            row = []
            for j in range (0,length):
                row.append(0)
            self.mat.append(row)

        for i in range (0,length):
            self.__Sub_row(i)


    def __EnlargeMat (self): #扩充mat
        for i in range (0,len(self.mat)): #每行加一列
            self.mat[i].append(0)

        self.mat.append([])

        for i in range (0,len(self.mat)): #新增一行
            self.mat[len(self.mat)-1].append(0)


    def __Sub_row (self,index): #构造mat的一行（index为子串）
        length = len(self.word_list)
        pattern_str = self.word_list[index]

        for i in range (0,length): #依次求第i个词是否为index父串
            string = self.word_list[i]

            if len(re.findall(pattern_str,string)) != 0 and i != index:#找真子串
                self.mat[index][i] = 1


    def __Sub_col (self,index): #构造mat的一列（index为父串）
        length = len(self.word_list)
        string = self.word_list[index]

        for i in range (0,length): #依次求第i个词是否为index父串
            pattern_str = self.word_list[i]

            if len(re.findall(pattern_str,string)) != 0 and i != index: #找真子串
                self.mat[i][index] = 1


    def AddWords (self,words): #为本地文本数据集添加列
        new_words = []
        start = self.col - 1

        for i in range (0,len(words)):
            word = words[i]
            count = 0

            for j in range (0,len(self.word_list)):
                if word == self.word_list[j]: #有重复
                    break
                count += 1

            if count < len(self.word_list): 
                continue

            self.word_list.append(word) #无重复时，更新字典和数据集
            new_words.append(word)
            self.Data[word] = 0
        
        self.col = self.Data.shape[1]
        self.datasize = self.Data.shape[0]

        for i in range (0,len(new_words)): #扩充与更新分开，避免出现更新时mat长度比word_list短
            self.__EnlargeMat()

        for i in range (0,len(new_words)): #更新矩阵
            self.__Sub_row(i+start)
            self.__Sub_col(i+start)

        return len (new_words)


    def AddSample (self,sample): #添加样本
        self.Data = pd.concat([self.Data,sample])
        self.datasize += 1


    def __WordInx (self,word):
        length = len(self.word_list)
        word_inx = length

        for i in range (0,length): #找到词汇索引
            if word == self.word_list[i]:
                word_inx = i
                break

        return word_inx


    def __LongerWords (self,word): #找到以word为子串的词语
        length = len(self.word_list)
        longer_words = []
        word_inx = self.__WordInx(word)

        for i in range (0,length):
            if self.mat[word_inx][i] == 1:
                longerword_inx = self.__WordInx(self.word_list[i])
                longer_words.append(longerword_inx)

        return longer_words

    
    def TextSample (self,text): #文本到样本转换
        length = len(self.word_list)

        dict = {'Emotion':0}
        for i in range (0,len(self.word_list)):
            dict[self.word_list[i]] = 0

        sample = pd.DataFrame([dict]) #构建空样本
        
        is_match = []

        for i in range (0,length): #is_match用来存放每一个词语是否已经被匹配过
            is_match.append(0)

        for i in range (0,length):
            if is_match[i] == 1: #本词语已经被匹配过
                continue

            word = self.word_list[i] #词语
            match = re.findall(word,text) #匹配串
            is_match [i] = 1

            if len(match) != 0: #该词语存在于文本中
                longer_words = self.__LongerWords(word)

                match_len = len(word)
                match_inx = i

                for j in range (0,len(self.mat[0])): #设置匹配的串的子串不配再次匹配
                    if self.mat[j][i] == 1:
                        is_match[j] = 1
                
                for j in range (0,len(longer_words)): 
                #找是否有比word更长的，以word为子串的词语存在于文本中
                    match = re.findall(self.word_list[longer_words[j]],text)
                    is_match [longer_words[j]] = 1 #将本词语设置为已匹配过

                    if (len(match) != 0 and len(self.word_list[longer_words[j]]) > match_len): 
                    #找到了这样的词语
                        match_len = len(self.word_list[longer_words[j]])
                        match_inx = longer_words[j]
                
                sample.iloc[0,match_inx+1] = 1

        return sample